﻿using Flurl.Http;
using furion.blog.Application.Contracts;
using furion.blog.Domain.Shared.Vo.Location;
using Furion;
using Furion.DependencyInjection;
using Furion.JsonSerialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace furion.blog.Application
{
    public class LocationService : ILocationService, ISingleton
    {
        private readonly IEmailService _emailService;

        public LocationService(IEmailService emailService) {
            this._emailService = emailService;
        }

        /// <summary>
        /// 通过经维度获取位置信息
        /// </summary>
        /// <param name="lat"></param>
        /// <param name="lng"></param>
        /// <returns></returns>
        public async Task<LocationVO> Info(string lat, string lng)
        {
            string ret = string.Empty;
            int tryTimes = 3;//尝试请求次数
            string url = string.Format("https://api.map.baidu.com/geocoder?location={0},{1}&output=json", lat, lng);
            while (string.IsNullOrEmpty(ret) && tryTimes <= 3)
            {
                ret = await url.GetStringAsync();
            }
            if (string.IsNullOrEmpty(ret)) {
                //请求失败,发送邮件通知管理人员
                await this._emailService.Send(new Domain.Shared.Dto.Email.EmailSendDto {
                   Title = "百度地理位置接口请求失败",
                   Content = "请求地址："+url,
                   From = App.Configuration["Email:Sender:Email"],
                   To = App.Configuration["Email:Sender:Email"],
                });
                return null;
            }
            JObject json = (JObject)JsonConvert.DeserializeObject(ret);
            if (json.ContainsKey("status") && json.Value<string>("status").ToLower() == "ok")
            {
                //请求成功
                JObject ac = (json.Value<JObject>("result")).Value<JObject>("addressComponent");
                return new LocationVO { 
                    Lat = lat,
                    Lng = lng,
                    City = ac.Value<string>("city"), 
                    Addr = (json.Value<JObject>("result")).Value<string>("formatted_address")
                };
            }
            else { 
               //请求失败
               return new LocationVO { };
            }
        }

    }
}
